package com.example.backed.controller;

import com.example.backed.common.ApiResponse;
import com.example.backed.dto.ProductQuery;
import com.example.backed.dto.ProductRequest;
import com.example.backed.entity.Product;
import com.example.backed.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "商品管理", description = "商品相关接口")
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    @Operation(summary = "创建商品")
    @PostMapping
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ApiResponse<Product> createProduct(@Valid @RequestBody ProductRequest request) {
        return ApiResponse.success(productService.createProduct(request));
    }

    @Operation(summary = "更新商品")
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ApiResponse<Product> updateProduct(@PathVariable Long id, @Valid @RequestBody ProductRequest request) {
        return ApiResponse.success(productService.updateProduct(id, request));
    }

    @Operation(summary = "删除商品")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ApiResponse<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return ApiResponse.success("删除成功", null);
    }

    @Operation(summary = "获取商品详情")
    @GetMapping("/{id}")
    public ApiResponse<Product> getProduct(@PathVariable Long id) {
        return ApiResponse.success(productService.getProduct(id));
    }

    @Operation(summary = "查询商品列表")
    @GetMapping
    public ApiResponse<Map<String, Object>> listProducts(ProductQuery query) {
        List<Product> products = productService.listProducts(query);
        long total = productService.countProducts(query);
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", products);
        result.put("total", total);
        
        return ApiResponse.success(result);
    }

    @Operation(summary = "更新商品库存")
    @PutMapping("/{id}/stock")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    public ApiResponse<Boolean> updateStock(@PathVariable Long id, @RequestParam Integer stock) {
        return ApiResponse.success(productService.updateStock(id, stock));
    }
} 